import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import Cart from '@/views/Cart.vue'
import Address from '@/views/Address.vue'
import OrderConfirm from '@/views/order/Confirm.vue'
import OrderReview from '@/views/order/Review.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Home',
      component: () => import('../views/Home.vue')
    },
    {
      path: '/products',
      name: 'Products',
      component: () => import('../views/Products.vue')
    },
    {
      path: '/orders',
      name: 'Orders',
      component: () => import('../views/Orders.vue'),
      meta: { requiresAuth: true }  // 需要登录才能访问
    },
    {
      path: '/about',
      name: 'About',
      component: () => import('../views/About.vue')
    },
    {
      path: '/cart',
      name: 'Cart',
      component: Cart
    },
    {
      path: '/address',
      name: 'Address',
      component: Address
    },
    {
      path: '/tracking',
      name: 'Tracking',
      component: () => import('../views/Tracking.vue')
    },
    {
      path: '/theme/:id',
      name: 'Theme',
      component: () => import('../views/Theme.vue'),
    },
    {
      path: '/theme/:id/reviews',
      name: 'ThemeReviews',
      component: () => import('../views/ThemeReviews.vue'),
      props: true
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../views/auth/Login.vue')
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('../views/auth/Register.vue')
    },
    {
      path: '/profile',
      name: 'Profile',
      component: () => import('../views/Profile.vue'),
      meta: {
        requiresAuth: true,
        title: '个人中心'
      }
    },
    {
      path: '/order/confirm',
      name: 'OrderConfirm',
      component: OrderConfirm
    },
    {
      path: '/orders/:orderId/items/:itemId/review',
      name: 'OrderReview',
      component: OrderReview,
      props: true
    }
  ]
})

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  // 需要登录的路由
  const requiresAuth = ['/cart', '/orders', '/address']

  if (requiresAuth.includes(to.path) && !userStore.token) {
    ElMessage.warning('请先登录')
    next('/login')
  } else {
    document.title = `${to.meta.title || '花伴'}`
    next()
  }
})

export default router
